package com.himiotech.core.project.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.himiotech.core.project.data.dao.JdbcDao;
import com.himiotech.core.project.service.IGenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author wuwenbin
 */
@Service
@Transactional(readOnly = true)
public class GenServiceImpl implements IGenService {

    @Autowired
    private JdbcDao jdbcDao;

    @Override
    public Page<Map<String, Object>> tableTodoListPage(Page<Map<String, Object>> page, Map<String, Object> searchParam) {

        String sql = "select " +
                "table_name,table_comment,DATE_FORMAT(create_time,'%Y-%m-%d %H:%m:%s') as create_time," +
                "DATE_FORMAT(update_time,'%Y-%m-%d %H:%m:%s') as update_time " +
                "from information_schema.tables " +
                "where table_schema = (select database()) " +
                "and table_name NOT IN (select table_name from gen_table) " +
                "and table_name NOT LIKE 'qrtz_%' and table_name NOT LIKE 'gen_%' ";

        if (MapUtil.isNotEmpty(searchParam)) {
            String tableName = MapUtil.getStr(searchParam, "table_name");
            if (StrUtil.isNotEmpty(tableName)) {
                searchParam.put("table_name", "%" + tableName + "%");
                sql += " and table_name like :table_name";
            }
            String tableComment = MapUtil.getStr(searchParam, "table_comment");
            if (StrUtil.isNotEmpty(tableComment)) {
                searchParam.put("table_comment", "%" + tableComment + "%");
                sql += " and table_comment like :table_comment";
            }
        }


        //目前只支持单列排序
        List<OrderItem> orders = page.getOrders();
        String orderSql = "order by ";
        if (CollectionUtil.isNotEmpty(orders)) {
            orderSql = orderSql.concat(orders.get(0).getColumn()).concat(orders.get(0).isAsc() ? " asc" : " desc");
        } else {
            orderSql = orderSql.concat("create_time desc,update_time desc");
        }
        sql = StrUtil.format(sql, orderSql);

        return jdbcDao.findPageListMapByMap(sql, page, searchParam);
    }


}
